<template>
  <basic-container class="app-container">
    <div v-if="!isManage">
      <div class="filter-container">
        <el-button
          class="filter-item"
          size="small"
          type="primary"
          v-waves
          icon="el-icon-plus"
          @click="handleAdd"
          >添加</el-button
        >
        <!-- <el-select v-model="parameter.showFlag" placeholder="请选择" size="small">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button
          icon="el-icon-document"
          size="small"
          type="primary"
          @click="loadData()"
          >搜索</el-button
        >
         -->
      </div>

      <div>
        <tree-grid
          :columns="columns"
          :tree-structure="true"
          :data-source="goods_category_rows"
        >
          <div slot="op-template" slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <!-- <el-button
              size="mini"
              type="success"
              @click="handleManage(scope.row)"
              >管理商品</el-button
            > -->
          </div>
        </tree-grid>
      </div>

      <el-dialog
        :title="isEditing ? '修改' : '添加'"
        :visible.sync="dialogFormVisible"
        width="1000px"
      >
        <el-form
          class="dialog-form"
          :rules="rules"
          ref="dataForm"
          :model="formData"
          label-position="left"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="分类名称" prop="categoryName">
                <el-input
                  v-model="formData.categoryName"
                  placeholder="不超过6个字符"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="选择上级分类" prop="parentId">
                <el-cascader
                  placeholder="选择上级分类"
                  :options="goods_cascader"
                  v-model="formData.parentId"
                  filterable
                  @change="handleActive"
                  change-on-select
                ></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否前端展示">
                <el-radio-group v-model="formData.showFlag">
                  <el-radio :label="0" :value="0">否</el-radio>
                  <el-radio :label="1" :value="1">是</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="排序" prop="sortNum">
                <el-input
                  v-model.number="formData.sortNum"
                  type="number"
                  placeholder="排序"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12" :class="{ 'active': isActive }">
              <el-form-item label="分类小图标 (100 x 100)" prop="categoryImg" >
                <el-upload
                  class="avatar-uploader"
                  :action="UPLOAD_URL"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess('categoryImg')"
                  :before-upload="beforeAvatarUpload"
                >
                  <img
                    v-if="formData.categoryImg"
                    :src="formData.categoryImg"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" :loading="submiting" @click="submitFormAction"
            >确定</el-button
          >
        </div>
      </el-dialog>
    </div>
    <router-view></router-view>
  </basic-container>
</template>

<script>
import { TreeGrid } from "@/components/treeTable";
import * as apiGoodsCategory from "@/api/goodsCategory";

export default {
  components: {
    TreeGrid,
  },
  filters: {
    filterShowFlag(row) {
      return ["否", "是"][row];
    },
  },
  watch: {
    $route () {
      if (this.$route.name == 'goods.goods_category.manage') {
        this.isManage = true
      } else {
        this.isManage = false
      }
    }
  },
  data() {
    return {
      submiting:false,
      isEditing:true,
      isActive:false,
      isManage: false,
      defaultProps: {
        children: "childList",
        label: "categoryName",
      },
      options: [
        {
          value: "0",
          label: "否",
        },
        {
          value: "1",
          label: "是",
        },
      ],
      parameter: {
        showFlag: "",
      },
      columns: [
        {
          text: "分类名称",
          dataIndex: "categoryName",
        },
        {
          text: "分类排序",
          dataIndex: "sortNum",
        },
        {
          text: "是否前端展示",
          dataIndex: "_showFlag",
        },
      ],
      goods_category_rows: [],
      goods_cascader: [],
      parentCategories: [
        {
          value: "0",
          label: "root",
        },
      ],
      formData: {
        id: "",
        title: "",
        parentId: "",
        code: "",
        thumbImg: "",
        thumbBigImg: "",
        sort: 0,
        categoryImg:""
      },
      typeIdOptions: [],
      id:"",
      goodsParameter:{
        id:"",
        pageNo:1,
        pageSize:50
      },
      dialogFormVisible:false,
      goodsDialogFormVisible:false,
      rules: {
        categoryName: [
          {
            required: true,
            message: "开始时间不能为空",
            trigger: "change",
          },
          {
            max: 6,
            trigger: "change",
            message: "不超过6个字符",
          },
        ],
        title: [
          {
            required: true,
            trigger: "change",
            message: "请输入分类名称",
          },
          {
            max: 20,
            trigger: "change",
            message: "不超过20个字符",
          },
        ]
      },
    };
  },
  created() {
    this.loadData();

    if (this.$route.name == 'goods.goods_category.manage') {
      this.isManage = true
    } else {
      this.isManage = false
    }
  },
  methods: {
    handleActive(e){
      if(e[0] != '0'){
        this.isActive=true
      }else{
        this.isActive=false
      }
    },
    handleManage (row) {
      this.$router.push('/category-manage?id=' + row.id)
    },
    handleAdd() {
      // Object.assign(this.formData, {});
      this.formData={}
      this.isEditing = false;
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.formData = row;
      this.isEditing = true;
      this.dialogFormVisible = true;
    },
    loadData() {
      const itemFunc = item => item._showFlag = item.showFlag == 1 ? "是" : "否";
      apiGoodsCategory.list(this.parameter)
     .then((info) => {
        if(!info){
          this.goods_cascader = [{ value: "0", label: "顶级分类" }];
          return
        }
        let option=[{ value: "0", label: "顶级分类" }]
        info.forEach(item => {
          option.push({
            value:item.id,
            label:item.categoryName
          })
          itemFunc(item)
          item.children = item.childList || [];
          item.children.forEach((data)=>{
            itemFunc(data)
          })
        });
        this.goods_category_rows = info;
        // this.goods_cascader = [{ value: "0", label: "顶级分类" }, ...info];
        this.goods_cascader = option;
      });
    },
    downloadFile() {
      let url = "/excels/商品分类导入模板.xlsx";
      this.openWin(url);
    },
    handleDelete(row) {
      this.$confirm("确认要删除吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        apiGoodsCategory.removeById(row.id)
          .then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.loadData();
          })
          .catch((info) => {});
      });
    },
    submitFormAction() {
      this.$refs["dataForm"].validate((valid) => {
        console.log(this.formData)
        console.log(this.formData.parentId)
        if (valid) {
          if(this.formData.parentId[0] != '0'){
            if(!this.formData.categoryImg){
              this.$message.error('请上传图片');
              return
            }
          }
          this.submiting = true;
          let func = null;
          if (this.isEditing) {
            func = apiGoodsCategory.update(this.formData)
          } else {
            func = apiGoodsCategory.create(this.formData)
            this.isEditing = false;
          }
          func
            .then(() => {
              this.submiting = false;
              this.dialogFormVisible = false;
              this.$notify({
                title: "成功",
                message: "操作成功",
                type: "success",
                duration: 2000,
              });
              this.loadData();
            })
            .catch((info) => {
              this.submiting = false;
            });
        }
      });
    },
    // __onRowRemoved() {
    //   this.$post("/admin/goods_promotion_category/list_all").then((info) => {
    //     this.goods_category_rows = info;
    //   });
    //   return false;
    // },
    // __onFormSubmited() {
    //   this.$post("/admin/goods_promotion_category/list_all").then((info) => {
    //     this.goods_category_rows = info;
    //   });
    //   return false;
    // },
    handleAvatarSuccess(imgField) {
      return (res, file) => {
        if (res && res.code === 200) {
          this.formData[imgField] = res.data;
          this.$set(this.formData, imgField, res.data)
          this.$forceUpdate()
        }
      };
    },
    __onAfterHandleEditUpdate(row) {
      Object.assign(this.formData, this.temp);
    },
    __onHandleUpdate(row) {
      if (row) {
        this.$post("/admin/goods_category/tree").then((info) => {
          this.parentCategories = [
            {
              value: "0",
              label: "(顶级分类)",
            },
          ];
          for (let i = 0; i < info.length; i++) {
            let el = info[i];
            if (el.value == row.id) {
              info.splice(i, 1);
              break;
            }
          }
          this.parentCategories.push(...info);
        });

        if (typeof row.parentId !== "object") {
          let pidStr = row.path.replace("," + row.id + ",", "").trim(",");
          if (pidStr) {
            row.parentId = pidStr.split(",");
          } else {
            row.parentId = ["0"];
          }
        }
      } else {
        this.formData = {};
        this.$post("/admin/goods_category/tree").then((info) => {
          this.parentCategories = [
            {
              value: "0",
              label: "(顶级分类)",
            },
          ];
          this.parentCategories.push(...info);
        });
      }
    },
    onImportSuccess(res, file, list) {
      list.length = 0;
      if (res.errcode == 1) {
        this.$message.error(res.msg);
        return;
      }
      this.$$notify("导入成功");
    },
    __onFormSubmit() {
      Object.assign(this.temp, this.formData);
      if (this.isEditing) {
        // for 编辑
        this.temp.categoryId = this.temp.id;
        if (this.temp.parentId[this.temp.parentId.length - 1] == this.temp.id) {
          this.$alert("上级分类不能是它自己");
          return false;
        }
      }
      this.temp.parentId = this.temp.parentId[this.temp.parentId.length - 1];
    },
    exportExcelFile() {
      this.exportExcel({
        title: "商品分类",
        fields: [
          {
            field: "title",
            title: "分类名称",
          },
        ],
      }).then((info) => {
        this.openWin(info);
      });
    },
  },
};
</script>

<style scoped>
.avatar-uploader,.avatar{
  width: 100px;
}
.active::before{
  display: flex;
  content: '*';
  color: #F56C6C;
  margin-right: 4px;
  margin-top: 12px;
  position: absolute;
    left: 3px;
}
</style>
